<template>
  <el-form
    :model="loggin"
    status-icon
    :rules="logginYZ"
    ref="loggin"
    class="mar_top"
  >
    <el-form-item label prop="username">
      <el-col :span="24">
        <el-input placeholder="请输入用户名" v-model="loggin.username">
          <i slot="prefix" class="el-input__icon fa fa-user-o"></i>
        </el-input>
      </el-col>
    </el-form-item>
    <el-form-item label prop="password">
      <el-col :span="24">
        <el-input
          placeholder="密码"
          :show-password="true"
          type="password"
          v-model="loggin.password"
        >
          <i slot="prefix" class="el-input__icon fa fa-lock"></i>
        </el-input>
      </el-col>
    </el-form-item>

    <el-form-item label prop="dx_code" v-if="isOpen == 1">
      <el-col :span="24">
        <el-col :span="13">
          <el-input
            placeholder="请输入短信验证码"
            maxlength="4"
            v-model="loggin.dx_code"
          >
            <i slot="prefix" class="el-input__icon fa fa-phone"></i>
          </el-input>
        </el-col>
        <el-col :span="1" style="height: 2.5rem"></el-col>
        <el-col :span="10" class="tr">
          <el-button
            :loading="$store.state.isLoading"
            @click="sendcode()"
            :disabled="!canClick"
            >{{ content }}</el-button
          >
        </el-col>
      </el-col>
    </el-form-item>

    <el-form-item label prop="code">
      <el-col :span="14">
        <el-input
          placeholder="验证码"
          maxlength="4"
          @keyup.enter.native="loginAdmin('loggin')"
          v-model="loggin.code"
        >
          <i slot="prefix" class="el-input__icon fa fa-photo"></i>
        </el-input>
      </el-col>
      <el-col :span="2" style="height: 2.5rem"></el-col>
      <el-col :span="8" style="height: 2.5rem" class="pd_left_">
        <img class :src="codeUrl" @click="getCodeImg" />
      </el-col>
    </el-form-item>
    <el-form-item class="tl">
      <el-col :span="24">
        <el-checkbox v-model="isLogin">
          勾选代表同意
          <a href="#" class="sizeColor_lan">【授权使用协议】</a>
        </el-checkbox>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-col :span="24">
        <el-button
          :loading="$store.state.isLoading"
          :disabled="loada"
          :autofocus="true"
          @click="loginAdmin('loggin')"
          class="btn_login"
          >{{ logText }}
        </el-button>
      </el-col>
    </el-form-item>
  </el-form>
</template>
<script>
import Cookies from "js-cookie";
export default {
  name: "passLogin",
  components: {},
  props: {
    isOpen: {
      type: String,
      default: "0",
    },
  },
  data() {
    // eslint-disable-next-line no-useless-escape
    var ex = /^[A-Za-z0-9\-\_]+$/;
    var checkUser = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        //  setTimeout(() => {
        if (!this.$fnc.regexp(ex, value)) {
          callback(new Error("用户名非法"));
        } else {
          callback();
        }
        // }, 1000)
      }
    };
    // eslint-disable-next-line no-unused-vars
    var checkPsss = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      } else {
        if (!this.$fnc.regexp(ex, value)) {
          callback(new Error("密码非法"));
        } else {
          callback();
        }
      }
    };
    return {
      loggin: {
        username: "",
        password: "",
        code: "",
        unicode: "",
        dx_unicode: "",
        dx_code: "",
      },
      isLogin: true,
      logText: "登录",
      loada: false,
      codeUrl: "",
      logginYZ: {
        username: [{ validator: checkUser, trigger: "blur" }],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          { min: 4, max: 4, message: "请输入4位验证码", trigger: "blur" },
        ],
      },
      content: "发送验证码",
      totalTime: 60,
      canClick: true,
    };
  },
  methods: {
    sendcode() {
      var data = {};
      data["tel"] = this.loggin.username;
      this.$api.login.sendcode(data).then((res) => {
        if (res.data.code == 200) {
          this.loggin.dx_unicode = res.data.result;
          this.countDown(); //倒计时
        } else {
          this.$swal("操作失败！", res.data.result, "error");
        }
      });
    },
    countDown() {
      if (!this.canClick) return; //防重复点击
      this.canClick = false;
      let clock = window.setInterval(() => {
        this.totalTime--;
        this.content = this.totalTime + "s后重新发送";
        if (this.totalTime < 0) {
          //当倒计时小于0时清除定时器
          window.clearInterval(clock);
          this.content = "发送验证码";
          this.totalTime = 60;
          this.canClick = true; //这里重新开启
        }
      }, 1000);
    },
    getChildData(val) {
      this.value2 = val;
    },
    loginAdmin(formName) {
      this.$refs[formName].validate((valid) => {
        if (!this.isLogin) {
          this.$fnc.alertError("登录失败", "请授权使用协议");
          return;
        } else if (valid) {
          this.loada = true;
          this.logText = "登录中";
          var data = {
            username: this.loggin.username,
            password: this.$getCode(this.loggin.password),
            code: this.loggin.code,
            unicode: this.unicode,
            dx_unicode: this.loggin.dx_unicode,
            dx_code: this.loggin.dx_code,
          };
          this.$api.login.login(data).then((res) => {
            if (res.data.code == 200) {
              localStorage.setItem("adminuid", res.data.result.uid);
              localStorage.setItem("admin_key", res.data.result.key);

              Cookies.set("adminuid", res.data.result.uid, { expires: 30 });
              Cookies.set("admin_key", res.data.result.key, { expires: 30 });
              this.$store.commit(
                "setAdminname",
                res.data.result.username || ""
              );
              if (res.data.result.first_menu) {
                localStorage.setItem(
                  "first_menu",
                  res.data.result.first_menu || ""
                );
              }
              if (
                this.$route.query.redirect &&
                this.$route.query.redirect.indexOf("/login") < 0
              ) {
                let redirect = this.$route.query.redirect;
                this.$router.push(redirect);
                this.$store.dispatch("getHeadInfo");
                this.$store.commit("setTzUrl", redirect);
              } else {
                if (res.data.result.first_menu) {
                  this.$router.push(res.data.result.first_menu);
                } else {
                  this.$router.push("/index");
                }
              }
            } else {
              this.getCodeImg();
              this.loada = false;
              this.$fnc.alertError(res.data.code_desc, res.data.result);
            }
            this.loada = false;
            this.logText = "登录";
          });
        } else {
          return false;
        }
      });
    },
    getCodeImg() {
      this.unicode = parseInt(Math.random() * 10000);
      this.codeUrl = "/api/common/code/index";
      this.codeUrl = this.codeUrl + "?unicode=" + this.unicode;
    },
  },
  created() {
    this.getCodeImg();
  },
};
</script>

<style lang="less" scoped>
.row {
  height: 42px;
  line-height: 42px;
  border: 1px solid #e3e7ed;
  position: relative;
  border-radius: 0.25rem;
  div > i {
    padding-left: 10px;
    color: #e3e7ed;
    font-size: 1.3rem;
    display: inline-block;
    line-height: 2;
  }
}
.i1 {
  padding-right: 10px;
}
.phont_text {
  cursor: pointer;
  display: inline-block;
  line-height: 2.5rem;
}
.phont_text + i {
  padding: 0 10px;
  cursor: pointer;
}
form input {
  background: transparent;
}
.el-checkbox {
  width: 100% !important;
}
.codeImg {
  height: 2.5rem;
}
.btn_login {
  width: 100%;
  color: #fff;
  border-color: #5dd5c8;
  background-color: #5dd5c8;
}
.btn_login:hover {
  color: #333;
  border-color: #ddd;
  background-color: #fff;
}
</style>
